package com.jiaquyun.jcyx.jetpack.mode

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.jiaquyun.jcyx.app.AppConstance
import com.jiaquyun.jcyx.app.JCApplication
import com.jiaquyun.jcyx.entity.*
import com.jiaquyun.jcyx.base.BaseViewModel
import com.module.lemlin.http.HttpResponseBody
import com.module.lemlin.http.SubscribeViewModel
import com.jiaquyun.jcyx.db.CartSelected
import com.jiaquyun.jcyx.jetpack.api.CartRepository
import com.module.lemlin.http.HttpResponseData
import org.greenrobot.eventbus.EventBus
import java.lang.StringBuilder

open class CartViewModel(application: Application) : BaseViewModel(application) {

    private val mCartRepository = CartRepository()

    val cartIndexLiveData = MutableLiveData<HttpResponseBody<CartResponse>>()

    /**
     * 购物车列表
     * */
    fun cartIndex() {
        val listener = object : SubscribeViewModel<CartResponse>(cartIndexLiveData) {
            override fun onSuccess(resp: CartResponse) {
                resp.data.goods_list?.forEach {
                    it.isSelected = JCApplication.appDatabase.accountDao()
                        .selectCartSelectedByShopIdAndCartId(55, it.cart_id) != null
                }
                super.onSuccess(resp)
                AppConstance.cartListLiveData.postValue(resp.data.goods_list)
            }
        }
        setRxLifeScope(listener) {
            mCartRepository.cartIndex()
        }
    }

    val cartAdd1LiveData = MutableLiveData<HttpResponseBody<CartActionResponse>>()
    fun cartAdd1(goodsId: Int, goodsNum: Int) {
        setRxLifeScope(object : SubscribeViewModel<CartActionResponse>(cartAdd1LiveData) {
            override fun onSuccess(resp: CartActionResponse) {
                val data = resp.data.apply {
                    this.goodsId = goodsId
                    this.goodsNum = goodsNum
                    this.isSelected = true
                    this.action = CartAction.Action.INSERT
                }
                EventBus.getDefault().post(data)
                updateCartListLiveData(data)
                super.onSuccess(resp.apply { this.data = data })
            }
        }) {
            mCartRepository.cartAdd1(
                goodsId.toString(), goodsNum.toString()
            )
        }

    }

    val cartChangeNum1LiveData = MutableLiveData<HttpResponseBody<CartActionResponse>>()
    fun cartChangeNum1(
        goodsId: Int, cartId: Int, goodsNum: Int, isSelected: Boolean = true
    ) {
        setRxLifeScope(object : SubscribeViewModel<CartActionResponse>(cartChangeNum1LiveData) {
            override fun onSuccess(resp: CartActionResponse) {
                val data = CartAction(
                    cartId = cartId,
                    goodsId = goodsId,
                    goodsNum = goodsNum,
                    isSelected = isSelected,
                    action = CartAction.Action.UPDATE
                )
                EventBus.getDefault().post(data)
                updateCartListLiveData(data)
                super.onSuccess(resp.apply { this.data = data })
            }
        }) {
            mCartRepository.cartChangeNum1(
                goodsNum.toString(), cartId.toString()
            )
        }
    }


    val cartDelete1LiveData = MutableLiveData<HttpResponseBody<CartActionResponse>>()
    fun cartRemove(goodsId: Int, cartId: Int) {
        setRxLifeScope(object : SubscribeViewModel<CartActionResponse>(cartDelete1LiveData) {
            override fun onSuccess(resp: CartActionResponse) {
                val data = CartAction(
                    cartId = cartId,
                    goodsId = goodsId,
                    action = CartAction.Action.DELETE
                )
                EventBus.getDefault().post(data)
                updateCartListLiveData(data)
                super.onSuccess(resp.apply { this.data = data })
            }
        }) {
            mCartRepository.cartDelete1(cartId.toString())
        }
    }

    fun cartClear(cartIds: Array<Int>) {
        setRxLifeScope(object : SubscribeViewModel<CartActionResponse>(cartDelete1LiveData) {
            override fun onSuccess(resp: CartActionResponse) {
                val data = CartAction(
                    action = CartAction.Action.CLEAR
                )
                EventBus.getDefault().post(data)
                updateCartListLiveData(data)
                super.onSuccess(resp.apply { this.data = data })
            }
        }) {
            val stringBuilder = StringBuilder()
            for ((index: Int, id: Int) in cartIds.withIndex()) {
                if (index == cartIds.size - 1) {
                    stringBuilder.append(id)
                } else {
                    stringBuilder.append(id).append(",")
                }
            }
            mCartRepository.cartDelete1(stringBuilder.toString())
        }
    }

    val cartSettlementLiveData = MutableLiveData<HttpResponseBody<CartSettlementResponse>>()
    fun cartSettlement(cartIds: Array<Int>) {
        setRxLifeScope(SubscribeViewModel(cartSettlementLiveData)) {
            val stringBuilder = StringBuilder()
            for ((index: Int, id: Int) in cartIds.withIndex()) {
                if (index == cartIds.size - 1) {
                    stringBuilder.append(id)
                } else {
                    stringBuilder.append(id).append(",")
                }
            }
            mCartRepository.cartSettlement(cartIds)
        }
    }


    fun updateCartListLiveData(cartAction: CartAction) {

        val data = AppConstance.cartListLiveData.value
            ?: return
        when (cartAction.action) {
            CartAction.Action.CLEAR -> {
                data.clear()
            }
            CartAction.Action.DELETE -> {
                data.find { it.cart_id == cartAction.cartId }?.let {
                    data.remove(it)
                }
                updateCartListSelected(cartAction.goodsId, cartAction.cartId, (false))
            }
            CartAction.Action.UPDATE -> {
                data.find { it.cart_id == cartAction.cartId }?.apply {
                    this.goods_num = cartAction.goodsNum
                    this.isSelected = cartAction.isSelected
                    updateCartListSelected(this.goods_id, this.cart_id, this.isSelected)
                }
            }
            CartAction.Action.SELECT_ALL -> {
                for (index: Int in 0 until data.size) data[index].apply {
                    this.isSelected = cartAction.isSelected
                    updateCartListSelected(this.goods_id, this.cart_id, this.isSelected)
                }
            }
            CartAction.Action.SELECT_SINGLE -> {
                data.find { it.cart_id == cartAction.cartId }?.apply {
                    this.isSelected = cartAction.isSelected
                    updateCartListSelected(this.goods_id, this.cart_id, this.isSelected)
                }
            }
            CartAction.Action.INSERT -> {
                updateCartListSelected(cartAction.goodsId, cartAction.cartId, (true))
                cartIndex()
            }
        }

        AppConstance.cartListLiveData.postValue(data)
    }

    /**
     * 更改数据库购物车是否选中
     * */
    private fun updateCartListSelected(goodsId: Int, cartId: Int, isSelected: Boolean) {
        val shopId: Int = 55
        if (isSelected) {
            //新增
            JCApplication.appDatabase.accountDao().insert(CartSelected().apply {
                this.shopId = shopId
                this.goodsId = goodsId
                this.cartId = cartId
            })
        } else {
            //删除
            JCApplication.appDatabase.accountDao().delete(shopId, cartId)
        }
    }

}